package com.bgds.sys.rbac.controller;


import com.bgds.sys.common.pagevo.Result;
import com.bgds.sys.common.utils.ResultUtil;
import com.bgds.sys.rbac.domain.Role;
import com.bgds.sys.rbac.domain.RolePermission;
import com.bgds.sys.rbac.service.RolePermissionService;
import com.bgds.sys.rbac.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author lj
 */
@Slf4j
@RestController
@Api(description = "角色管理接口")
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;



    @Autowired
    private RolePermissionService rolePermissionService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation(value = "获取所有角色",notes = "获取所有角色",httpMethod = "GET")
    public Result<List<Role>> getAllRoles(){
        List<Role> list = roleService.findAll();
        return new ResultUtil<List<Role>>().setData(list);
    }

    @RequestMapping(value = "/addRole", method = RequestMethod.POST)
    @ApiOperation(value = "新增角色",notes = "新增角色",httpMethod = "POST")
    public Result<Object> addRole( Role role){
       return roleService.add(role);
    }

    @RequestMapping(value = "/editRolePerm",method = RequestMethod.POST)
    @ApiOperation(value = "分配权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", dataType = "Long", required = true, value = "角色ID"),
            @ApiImplicitParam(name = "permIds", dataType = "Long[]", value = "权限id数组")
    })
    public Result<Object> editRolePerm( Long roleId,
                                       Long[] permIds){
        //删除其关联权限
        rolePermissionService.deleteByRoleId(roleId);
        //分配新权限

        for(Long permId : permIds){
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permId);
            rolePermissionService.save(rolePermission);
        }
        return ResultUtil.success("操作成功");





    }

}
